package com.schoolgard.base.interceptor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.schoolegard.services.SchoolDataService;
import com.schoolegard.services.UsersService;
import com.schoolgard.entitybean.Role;
import com.schoolgard.entitybean.RoleOfUsers;
import com.schoolgard.entitybean.RolePrivilege;
import com.schoolgard.entitybean.Users;
import com.supersystem.utils.StringUtil;
import com.supersystem.utils.TypeUtils;

public class LoginFilter implements Filter{
	
	private UsersService userservice = null;
	private SchoolDataService schoolDataService = null;

	@Override
	public void destroy() {
		userservice = null;
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
	    HttpServletResponse response = (HttpServletResponse) res;
	    HttpSession session = request.getSession();
		String token = req.getParameter("token");
		String userId = req.getParameter("userId"); //获取用户
		Users user = (Users)session.getAttribute("user");
		
		if(user != null){ //如果已经登录，直接跳过
			chain.doFilter(req, res);
			
		/**
		 * 令牌不为null，第一次单点登陆跳转过来的情况，这里要校验令牌的合法性
		 * 校验合格之后检测用户是否存在，不存在则持久化到users表，并设置session
		 * userId必须不为null，否则不能登录
		 */
		}else if(token != null && userId != null && validateToken(token)){
			Users user1 = userservice.findByLoginId(userId);
			if(user1 == null){
				//TODO 根据传递过来的参数设置用户  organization必须设置,否则报警模块会报错
				user1 = new Users();
				user1.setLoginid(userId);
				user1.setName("管理员");
				userservice.saveOrUpdate(user1); //第一次登录保存一下，如果存在就是
			}
			setUserAuthority(user1 , session); //设置权限，菜单权限
			chain.doFilter(req, res);
		}else{//跳转到单点登录
			response.sendRedirect("http://www.baidu.com");
			return;
		}
	}
	
	/**
	 * 设置员工权限，菜单权限
	 * 根据员工id查找角色用户表，查找到角色
	 * 再根据所有角色id查找拥有的菜单(角色菜单表，既权限表)，需要去重
	 * 再将菜单id保存到session中
	 * @param user
	 */
	public void setUserAuthority(Users user , HttpSession session)
	{
		if(user == null) return;
		StringBuffer catalogs = new StringBuffer(); //菜单权限数据
		List<Role> roles = this.getRoles(user.getRoleOfUserses()); //获取角色
		/**
		 * 1、刚刚存入数据库，没有授权信息，为普通用户。
		 * 2、没有授权，也为普通用户
		 * 如果上述条件成立，则自动给user赋予普通用户的权力
		 * 系统默认admin和nomal两种用户。
		 */
		if(roles == null || roles.size() == 0){
			Role role = userservice.findRoleByRoleName("nomal");
			userservice.saveAuthority(user.getId(), role.getId().toString());
			roles.add(role);
		}
		for (Role role : roles) {
			Set<RolePrivilege> privileges = role!=null?role.getRolePrivileges():null;
			if(privileges != null && !privileges.isEmpty()){
				Iterator<RolePrivilege> ite = privileges.iterator();
				while(ite.hasNext()){
					catalogs.append(ite.next().getPrivilegeMenu()); //注意 ：默认保存的菜单格式为001,001001,最后面有一个逗号。
				}
			}
			
		}
		//设置当前用户的菜单权限
		session.setAttribute(TypeUtils.USER_CATALOG_IDS, StringUtil.delRepeatString(catalogs.toString()));
		session.setAttribute(TypeUtils.USER, user);
	}
	
	/**
	 * 根据角色用户表，获取用户的所有角色
	 * 一个用户可以对应多个角色
	 * @param roleTouser
	 * @return
	 */
	private List<Role> getRoles(Set<RoleOfUsers> roleTouser)
	{
		if(roleTouser.isEmpty()) {
			return new ArrayList<Role>();
		}
		Iterator<RoleOfUsers> ite = roleTouser.iterator();
		List<Role> roles = new ArrayList<Role>();
		StringBuffer rolebf = new StringBuffer();
		while(ite.hasNext()){
			rolebf.append(ite.next().getRole()).append(",");
		}
		String[] roleArray = StringUtil.delRepeatString(rolebf.toString()).split(",");
		for(int i = 0 ; i<roleArray.length ; i++){
			roles.add(userservice.findRoleById(Long.valueOf(roleArray[i].trim())));
		}
		return roles;
	}
	
	//TODO
	private boolean validateToken(String token){
		return true;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(arg0.getServletContext());
	    userservice = (UsersService)ac1.getBean("usersService");
	    schoolDataService = (SchoolDataService)ac1.getBean("schoolDataService");
	}

}
